import * as mysql from 'mysql2/promise';
import { config } from 'dotenv';

config();

async function recreateAll() {
  console.log('开始重新创建数据库和表...');
  
  const host = process.env.DB_HOST || 'localhost';
  const port = Number(process.env.DB_PORT) || 3306;
  const username = process.env.DB_USERNAME || 'root';
  const password = process.env.DB_PASSWORD || '123456';
  const database = process.env.DB_DATABASE || 'hdq-news';
  
  // 创建不指定数据库的连接
  const connection = await mysql.createConnection({
    host,
    port,
    user: username,
    password
  });
  
  try {
    console.log(`尝试删除数据库 ${database}...`);
    await connection.query(`DROP DATABASE IF EXISTS \`${database}\``);
    console.log(`数据库 ${database} 已删除`);
    
    console.log(`尝试创建数据库 ${database}...`);
    await connection.query(`CREATE DATABASE \`${database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`);
    console.log(`数据库 ${database} 已创建`);
    
    console.log('数据库重新创建完成，现在可以启动应用程序让 TypeORM 创建表');
  } catch (error) {
    console.error('重新创建数据库时出错:', error);
  } finally {
    await connection.end();
  }
}

recreateAll()
  .then(() => process.exit(0))
  .catch(error => {
    console.error(error);
    process.exit(1);
  });